import { createSlice, PayloadAction } from "@reduxjs/toolkit";

interface MenuState {
  selectedKeys: string[];
  openKeys: string[];
  tagList: { key: string; name: string }[];
}

const initialState: MenuState = {
  selectedKeys: [],
  openKeys: [],
  tagList: sessionStorage.getItem("tagList")
    ? JSON.parse(sessionStorage.getItem("tagList") as string)
    : [],
};

const menuSlice = createSlice({
  name: "menu",
  initialState,
  reducers: {
    setSelectedKeys(state, action: PayloadAction<string[]>) {
      state.selectedKeys = action.payload;
    },
    setOpenKeys(state, action: PayloadAction<string[]>) {
      state.openKeys = action.payload;
    },
    addTag(state, action: PayloadAction<{ key: string; name: string }>) {
      const tag = action.payload;
      // 确保标签唯一
      if (!state.tagList.some((t) => t.key === tag.key)) {
        state.tagList.push(tag);
        sessionStorage.setItem("tagList", JSON.stringify(state.tagList));
      }
    },
    removeTag(state, action: PayloadAction<string>) {
      state.tagList = state.tagList.filter((tag) => tag.key !== action.payload);
      sessionStorage.setItem("tagList", JSON.stringify(state.tagList));
    },
    removeAllTags(state) {
      state.tagList = [];
      sessionStorage.removeItem("tagList");
    },
  },
});

export const {
  setSelectedKeys,
  setOpenKeys,
  addTag,
  removeTag,
  removeAllTags,
} = menuSlice.actions;
export default menuSlice.reducer;
